const { User } = require("../models");
const jwt = require("jsonwebtoken");

exports.login = async (req, res, next) => {
  try {
    // 处理请求
    const { username, password } = req.body;
    let user = await User.findOne({ username });
    if (user) {
      // 登录
      if (password !== user.password) {
        return res.status(401).json({ message: "密码错误" });
      }
    } else {
      // 如果没有则注册
      user = await User.create({ username, password });
    }

    res.status(200).send({
      message: "登录成功",
      user: {
        username: user.username,
        token: jwt.sign(
          { userId: user._id },
          "a053e3a3-a00d-4c1f-b4bb-fd71e3aab361",
          { expiresIn: "24h" }
        ),
      },
    });
  } catch (error) {
    // 交给后面的错误处理中间件统一处理错误
    next(error);
  }
};
